<template>
  <div ref="formContainer" class="form-data">
    <h1>Form Data</h1>
    <form ref="form" @submit.prevent>
      <label>
        姓名
        <input type="text" v-model="formData.username" />
      </label>
      <label>
        男
        <input type="radio" name="gender" value="1" v-model="formData.gender" />
      </label>
      <label>
        女
        <input type="radio" name="gender" value="2" v-model="formData.gender" />
      </label>
      <input type="file" @change="handleFileChange" />
      <button @click="submitFormData">提交</button>
    </form>
  </div>
</template>

<script setup lang="ts">
const form = ref<HTMLFormElement | null>(null);
const formContainer = ref<HTMLDivElement | null>(null);

const formData = reactive<{
  username: string;
  gender: string;
  file: File | null;
}>({
  username: "",
  gender: "",
  file: null,
});

const response = ref();

async function submitFormData() {
  console.log(formData);
  const formdata = new FormData();
  formdata.append("username", formData.username);
  formdata.append("gender", formData.gender);
  formdata.append("file", formData.file as File);
  const { data } = await useFetch("/form", {
    method: "POST",
    body: formdata,
  });
  response.value = data.value;
}

function handleFileChange(event: Event) {
  const target = event.target as HTMLInputElement;
  const selectFile = target.files?.[0];
  if (selectFile) {
    formData.file = selectFile;
    const reader = new FileReader();

    reader.onload = function (e) {
      const url = e.target?.result as string;
      const img = document.createElement("img");
      img.src = url;
      formContainer.value?.appendChild(img);
    };

    reader.readAsDataURL(selectFile);
  }
}
</script>

<style lang="scss" scoped></style>
